package cn.tedu.mall1.user.service.impl;

import cn.tedu.mall1.base.exception.ServiceException;
import cn.tedu.mall1.base.response.StatusCode;
import cn.tedu.mall1.user.mapper.UserMapper;
import cn.tedu.mall1.user.pojo.dto.UserLoginDTO;
import cn.tedu.mall1.user.pojo.dto.UserRegDTO;
import cn.tedu.mall1.user.pojo.entity.User;
import cn.tedu.mall1.user.pojo.vo.UserVO;
import cn.tedu.mall1.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void reg(UserRegDTO userRegDTO) {
        log.debug("用户注册：userRegDTO{}",userRegDTO);
        UserVO userVO = userMapper.selectByPhone(userRegDTO.getPhone());
        if (userVO != null){
            throw new ServiceException(StatusCode.PHONE_ALREADY_EXISTS);
        }
        String randomUsername = generateRandomUsername(8); // 生成长度为 8 的随机用户名
        userRegDTO.setUsername(randomUsername); // 设置随机生成的用户名到 DTO
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreateTime(new Date());
        userMapper.insert(user);
    }

    private String generateRandomUsername(int length) {
        String CHARSET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        SecureRandom random = new SecureRandom();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int randomIndex = random.nextInt(CHARSET.length());
            sb.append(CHARSET.charAt(randomIndex));
        }
        return sb.toString();
    }


    @Override
    public UserVO login(UserLoginDTO userLoginDTO) {
        UserVO userVO = userMapper.selectByPhone(userLoginDTO.getPhone());
        if (userVO == null){
            throw new ServiceException(StatusCode.PHONE_ERROR);
        }
        if (!userVO.getPassword().equals(userLoginDTO.getPassword())){
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }
        return userVO;
    }

}
